<template>
    <el-dialog title="分配权限" :visible="showDialog" @close="cancelClick">
        <!-- node-key="id"表示使用id作为节点唯一标识  有了id标识，default-checked-keys可以设置默认选中节点 -->
        <!-- check-strictly可以设置父子节点不互相关联，可以只选中父节点 -->
        <el-tree ref="tree" :data="permissions" :props="{ label: 'name', children: 'children' }" show-checkbox default-expand-all
            node-key="id" :default-checked-keys="selectedIds" check-strictly>
        </el-tree>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancelClick">取 消</el-button>
            <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { assignPrem } from '@/api/setting'

export default {
    name: 'AssignPermission',
    props: {
        // 控制弹层显示
        showDialog: {
            type: Boolean,
            required: true
        },
        // 树形权限组
        permissions: {
            type: Array,
            required: true
        },
        // 当前角色已有的权限ID组
        selectedIds: {
            type: Array,
            required: true
        },
        // 当前角色id
        roleId: {
            type: String,
            required: true
        }
    },
    methods: {
        // 确认操作
        async confirmClick() {
            // getCheckedKeys方法可以获取已选中id组
            const idKeys = this.$refs.tree.getCheckedKeys()
            await assignPrem({id: this.roleId, permIds: idKeys})
            this.$message.success('分配权限成功')
            this.$emit('update:showDialog', false)
        },
        // 取消操作
        cancelClick() {
            // 清空当前已选中权限
            this.$emit('update:selectedIds', [])
            // 关闭弹层
            this.$emit('update:showDialog', false)
        }
    }
}
</script>